package main

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

type GormLogger struct {
	SlowThreshold time.Duration
}

func NewGormLogger() *GormLogger {
	return &GormLogger{
		SlowThreshold: 2 * time.Millisecond,
	}
}

var _ logger.Interface = (*GormLogger)(nil)

func (l *GormLogger) LogMode(lev logger.LogLevel) logger.Interface {
	return &GormLogger{}
}

func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
	log.Context(ctx).Infof(msg, data...)
}

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	log.Context(ctx).Warnf(msg, data...)
}

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	log.Context(ctx).Errorf(msg, data...)
}

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
	elapsed := time.Since(begin)
	sql, rows := fc()
	//if err != nil {
	//	log.Context(ctx).Errorf("SQL ERROR | biz=%v, sql=%v, rows=%v, elapsed=%v, error=%v", ctx.Value("biz"), sql, rows, elapsed, err)
	//}
	//if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
	//	log.Context(ctx).Warnf("Database Slow Log | biz=%v, sql=%v, rows=%v, elapsed=%v", ctx.Value("biz"), sql, rows, elapsed)
	//}
	log.Context(ctx).Info("Database Info Log | biz=%v, sql=%v, rows=%v, elapsed=%v", ctx.Value("biz"), sql, rows, elapsed)

}

func main() {
	fmt.Println("TestLog")
	db, err := gorm.Open(mysql.Open(`root:12345678@tcp(127.0.0.1:3306)/test1`), &gorm.Config{
		QueryFields: true,
		Logger:      NewGormLogger(),
	})
	if err != nil {
		panic(err)
	}

	var count int
	todayBatchTotalCountCtx := context.WithValue(context.Background(), "biz", "我的业务")
	err = db.WithContext(todayBatchTotalCountCtx).Table("test").
		Select("count(1)").Row().Scan(&count)
	if err != nil {
		panic(err)
	}
}
